<?php

namespace App\Models;

class Menu extends Base
{
    protected $hidden = ['created_at', 'updated_at'];

    // 转换数组为字符串
    public function setMetaAttribute($value){
        if (is_array($value) && $value){
            $this->attributes['meta'] = json_encode($value, JSON_UNESCAPED_UNICODE);
        } else {
            $this->attributes['meta'] = null;
        }
    }

    // 转换字符串为数组
    public function getMetaAttribute($value){
        return $value ? json_decode($value, true) : [];
    }
    
    // 转换数组为字符串
    public function setPermissionAttribute($value){
        if (is_array($value) && $value){
            $this->attributes['permission'] = json_encode($value, JSON_UNESCAPED_UNICODE);
        } else {
            $this->attributes['permission'] = null;
        }
    }

    // 转换字符串为数组
    public function getPermissionAttribute($value){
        return $value ? json_decode($value, true) : [];
    }
    
    /**
     * 权限分组（多对多关系）
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function roles() {
        return $this->belongsToMany(Role::class)->withPivot('permission')->using(MenuRole::class);
    }
}
